//
//  QianliParentNaviVC.swift
//  todoios
//
//  Created by qianli on 2025/4/17.
//

import Foundation
import UIKit

//在非Navigation模式下，
//实现present 和 dismiss 时类似 push 和 pop的左右转场动画，而不是从下往上显示，从上往下消失
class QianliParentNaviVC: UIViewController {
    var dismissBlock: os_block_t?
    var titleBarView:UIView?
    let topSpace = UIDevice.qianli_statusbar_and_navibar_height()
    
    private var YSgwxXklgw9hk52r:MBProgressHUD?
    deinit {
        QianliUniversalFunc.QianliLog("------QianliParentNaviVC.deinit")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .secondarySystemBackground
        
        //实现present 和 dismiss 时类似 push 和 pop的转场动画，而不是从下往上显示，从上往下消失
        transitioningDelegate = self
        modalPresentationStyle = .custom
        // 添加滑动手势识别
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(yS6MCfrgkCJrCJGu))
        view.addGestureRecognizer(panGesture)
        
        self.GHL4Rhb91XYBer27()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        aB7kFqI8MB6DRPQC()
    }
    
    func GHL4Rhb91XYBer27(){
        
    }
    
    func aB7kFqI8MB6DRPQC(){
        
    }
    
    func zdMpsGrNncVEHdYA(title:String,textColor:UIColor = .label){
        let iTopJG = 10.0
        let iOKHeight = 36.0
        let titleBarHeight = iTopJG+iOKHeight
//---titlebar
        self.titleBarView = UIView(frame: CGRect(x: 0, y: topSpace-titleBarHeight, width: qianli_pm_width, height: titleBarHeight))
        if let topbarView = self.titleBarView{
            view.addSubview(topbarView)
            
            let label = UILabel(frame: CGRect(x: 100, y: 0, width: qianli_pm_width-200 , height: titleBarHeight))
            topbarView.addSubview(label)
            label.numberOfLines = 0
            label.textColor = textColor
            label.font = .boldSystemFont(ofSize: 18)
            label.text = title
            label.textAlignment = .center
            
            let iBtnWidth = 32.0
            let backBtn = UIButton(frame: CGRect(x: 15, y:titleBarHeight/2-iBtnWidth/2 , width: iBtnWidth, height: iBtnWidth))
            if let image = "qianli_back_page".qianli_R_image {
                let imageHeight = 24.0
                let imageWidth = 40.0*imageHeight/77.0
                // 创建按钮配置
                let resizedImage = image.try_qianli_resize(to: CGSize(width: imageWidth, height: imageHeight))?.withRenderingMode(.alwaysTemplate)
                //重设button内图标大小,并且设置为可改变填充颜色
                //同时改变图标位置：  imageEdgeInsets 15.0已弃用，故改用UIButton.Configuration
                var config = UIButton.Configuration.plain()
                config.image = resizedImage
                config.imagePadding = (iBtnWidth - imageWidth) / 2 // 设置图片的水平内边距
                config.baseForegroundColor = textColor
                // 将配置应用到按钮
                backBtn.configuration = config
            }
            topbarView.addSubview(backBtn)
            backBtn.touch_With_Block {[weak self] sender in
                QianliVibrateEnum.selection.L4smXfL531Hmh91R()
                self?.clFi25NuDNbscWXL()
            }
        }
    }
    
    func LPq07zWHcZ9thGLm(_ msg:String,_ delayTime:TimeInterval=1.5){
        DispatchQueue.main.async {[weak self] in
            if let self = self{
                self.l0JOXR3PG9RznwqZ()
                 
                self.YSgwxXklgw9hk52r = MBProgressHUD.showAdded(to: self.view, animated: true)
                if let hinthud = self.YSgwxXklgw9hk52r{
                    hinthud.mode = .text
                    hinthud.label.text = msg
                }
                self.perform(#selector(ApigP6H4dWrJ7Jm8), with: nil, afterDelay: delayTime)
            }
        }
    }
    
    @objc private func ApigP6H4dWrJ7Jm8(){
        if let hinthud = self.YSgwxXklgw9hk52r{
            hinthud.hide(animated: true)
        }
        self.YSgwxXklgw9hk52r = nil
    }
    
    func M62h1bVOydwY8i4y(_ msg:String){
        DispatchQueue.main.async {[weak self] in
            if let self = self{
                self.l0JOXR3PG9RznwqZ()
                 
                self.YSgwxXklgw9hk52r = MBProgressHUD.showAdded(to: self.view, animated: true)
                self.YSgwxXklgw9hk52r?.mode = .indeterminate
                if let loadingHud = self.YSgwxXklgw9hk52r,!msg.isEmpty{
                    loadingHud.label.text = msg
                }
            }
        }
    }
    
    @objc func l0JOXR3PG9RznwqZ(){
        if let loadingHud = self.YSgwxXklgw9hk52r{
            loadingHud.hide(animated: true)
        }
        self.YSgwxXklgw9hk52r = nil
    }
    
    @objc func clFi25NuDNbscWXL(){
        NSObject.cancelPreviousPerformRequests(withTarget: self)
        self.l0JOXR3PG9RznwqZ()
        self.dismissBlock?()
        dismiss(animated: true)
    }
    
    @objc func yS6MCfrgkCJrCJGu(_ gesture: UIPanGestureRecognizer) {
        let translation = gesture.translation(in: view)
        let progress = translation.x / view.bounds.width
        let velocity = gesture.velocity(in: view)

        switch gesture.state {
        case .changed:
            // 根据滑动距离更新视图的位置，实现类似从左往右滑动的效果
            if translation.x > 0 { //限定仅向右滑动才处理
                view.transform = CGAffineTransform(translationX: translation.x, y: 0)
            }
        case .ended:
            if translation.x > 0 {//限定仅向右滑动才处理
                print("velocity.x:",velocity.x)
                let shouldDismiss = progress > 0.4 || velocity.x > 500 //超过40%或速度较快时都执行关闭VC
                if shouldDismiss {
                    // 满足条件，执行关闭VC的操作
                    clFi25NuDNbscWXL()
                } else {
                    // 不满足条件，恢复视图位置
                    UIView.animate(withDuration: 0.25) {
                        self.view.transform = .identity
                    }
                }
            }
        default:
            break
        }
    }
    
    override func kx0EtJIP46fBMTgB(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true) //关闭键盘
    }
}

extension QianliParentNaviVC: UIViewControllerTransitioningDelegate {
//实现present 和 dismiss 时类似 push 和 pop的转场动画，而不是从下往上显示，从上往下消失
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        // 返回自定义的转场动画控制器，用于呈现动画
        return QianliVCTransitioningAnimator()
    }

    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        // 返回自定义的转场动画控制器，用于消失动画
        return QianliVCTransitioningAnimator()
    }
}
